package com.personal.portal.admin.service.impl;

import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.personal.portal.common.entity.Result;
import com.personal.portal.admin.entity.User;
import com.personal.portal.admin.mapper.PersonalProfileMapper;
import com.personal.portal.admin.service.PersonalProfileService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 个人信息服务实现类
 *
 * @author zhanghui
 * @version 1.0.0
 * @since 2025-11-13
 */
@Service
public class PersonalProfileServiceImpl implements PersonalProfileService {

    @Resource
    private PersonalProfileMapper personalProfileMapper;

    @Override
    public User queryById(Long id) {
        validateId(id);
        return personalProfileMapper.selectOneById(id);
    }

    @Override
    public User queryByEntity(User personalProfile) {
        QueryWrapper queryWrapper = buildQueryWrapper(personalProfile);
        return personalProfileMapper.selectOneByQuery(queryWrapper);
    }

    @Override
    public List<User> queryList(User personalProfile) {
        QueryWrapper queryWrapper = buildQueryWrapper(personalProfile);
        return personalProfileMapper.selectListByQuery(queryWrapper);
    }

    @Override
    public Result.PageResult<User> queryPage(int pageNum, int pageSize, User personalProfile) {
        QueryWrapper queryWrapper = buildQueryWrapper(personalProfile);
        Page<User> paginate = personalProfileMapper.paginate(pageNum, pageSize, queryWrapper);
        return new Result.PageResult<>(paginate.getRecords(), paginate.getTotalRow(), pageNum, pageSize);
    }

    @Override
    public int insert(User personalProfile) {
        validatePersonalProfile(personalProfile);
        return personalProfileMapper.insert(personalProfile);
    }

    @Override
    public int update(User personalProfile) {
        if (personalProfile.getId() == null) {
            throw new IllegalArgumentException("个人信息ID不能为空");
        }
        validateId(personalProfile.getId());
        validatePersonalProfile(personalProfile);

        User existing = personalProfileMapper.selectOneById(personalProfile.getId());
        if (existing == null) {
            throw new IllegalArgumentException("个人信息不存在");
        }

        return personalProfileMapper.update(personalProfile);
    }

    @Override
    public int deleteById(Long id) {
        validateId(id);

        User existing = personalProfileMapper.selectOneById(id);
        if (existing == null) {
            throw new IllegalArgumentException("个人信息不存在");
        }

        return personalProfileMapper.deleteById(id);
    }

    @Override
    public List<Long> deleteBatch(List<Long> ids) {
        if (ids == null || ids.isEmpty()) {
            throw new IllegalArgumentException("ID列表不能为空");
        }

        List<Long> successIds = new ArrayList<>();
        List<Long> failedIds = new ArrayList<>();

        for (Long id : ids) {
            try {
                validateId(id);

                User existing = personalProfileMapper.selectOneById(id);
                if (existing == null) {
                    failedIds.add(id);
                    continue;
                }

                int result = personalProfileMapper.deleteById(id);
                if (result > 0) {
                    successIds.add(id);
                } else {
                    failedIds.add(id);
                }
            } catch (Exception e) {
                failedIds.add(id);
            }
        }

        if (!successIds.isEmpty()) {
            return successIds;
        } else {
            throw new IllegalArgumentException("批量删除失败");
        }
    }

    @Override
    public User getPublicProfile() {
        // 查询公开显示且启用的个人信息
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getIsPublic, 1);
        queryWrapper.eq(User::getStatus, "enabled");
        queryWrapper.orderBy(User::getSortOrder, true);
        queryWrapper.orderBy(User::getId, true);

        List<User> profiles = personalProfileMapper.selectListByQuery(queryWrapper);
        return profiles != null && !profiles.isEmpty() ? profiles.get(0) : null;
    }

    /**
     * 验证个人信息
     */
    private void validatePersonalProfile(User personalProfile) {
        if (personalProfile == null) {
            throw new IllegalArgumentException("个人信息不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getName())) {
            throw new IllegalArgumentException("姓名不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getPosition())) {
            throw new IllegalArgumentException("职位不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getEmail())) {
            throw new IllegalArgumentException("邮箱不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getPhone())) {
            throw new IllegalArgumentException("电话号码不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getCity())) {
            throw new IllegalArgumentException("所在城市不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getWorkYears())) {
            throw new IllegalArgumentException("工作年限不能为空");
        }
        if (StringUtils.isBlank(personalProfile.getBio())) {
            throw new IllegalArgumentException("个人简介不能为空");
        }
    }

    /**
     * 验证ID
     */
    private void validateId(Long id) {
        if (id == null || id <= 0) {
            throw new IllegalArgumentException("无效的个人信息ID");
        }
    }

    /**
     * 构建查询条件
     */
    private QueryWrapper buildQueryWrapper(User personalProfile) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq(User::getId, personalProfile.getId(), personalProfile.getId() != null);
        queryWrapper.like(User::getName, personalProfile.getName(), StringUtils.isNotEmpty(personalProfile.getName()));
        queryWrapper.like(User::getPosition, personalProfile.getPosition(), StringUtils.isNotEmpty(personalProfile.getPosition()));
        queryWrapper.like(User::getEmail, personalProfile.getEmail(), StringUtils.isNotEmpty(personalProfile.getEmail()));
        queryWrapper.like(User::getCity, personalProfile.getCity(), StringUtils.isNotEmpty(personalProfile.getCity()));
        queryWrapper.eq(User::getIsPublic, personalProfile.getIsPublic(), personalProfile.getIsPublic() != null);

        queryWrapper.orderBy(User::getSortOrder, true);
        queryWrapper.orderBy(User::getName, true);
        queryWrapper.orderBy(User::getId, true);
        return queryWrapper;
    }
}
